package org.shs.user.action;

import static org.shs.common.config.SystemInitializer.app_msgs;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.shs.user.form.LoginForm;
import org.shs.user.model.UserModel;
import org.shs.user.service.UserService;

/**
 * Handles the user interaction coming in from the login screen
 * <br/>
 * <br/><b>Created:</b>&nbsp;&nbsp; 11-Nov-2008 23:57:23
 *
 * @author anirvan
 *
 */
public class LoginAction extends DispatchAction
{
   
   /**
    * The service class instance for this module
    */
   private static final UserService serviceCls = new UserService();
   
   /**
    * The logger instance to be used
    */
   private static Logger logger = Logger.getLogger(LoginAction.class);
   
   /* (non-Javadoc)
    * @see org.apache.struts.actions.DispatchAction#unspecified(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    */
   public ActionForward unspecified(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response)
   {
      return mapping.findForward("login");
   }
   
   /**
    * Validate the credentials of the user attempting to
    * log into the system.
    * @param mapping The action mapping instance
    * @param form  The (action) form bean associated
    * @param request The servlet HTTP Request object 
    * @param response The servlet HTTP response object
    * @return The forward mapping to be looked up in the 
    *         struts-config file.
    */
   public ActionForward validate(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response)
   throws Exception
   {
      String sForward = "", currTime = null;
      LoginForm formData = (LoginForm)form;
      HttpSession htSess = request.getSession(true);
      UserModel user = (UserModel) htSess.getAttribute("user"); 
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy | HH:mm:ss");
      Calendar cal = new GregorianCalendar();
      
      //Retrieve the current session id
      formData.setSessionId(htSess.getId());
      //Validate credentials of user logging in
      user = (user == null || user.getId() == null) ? 
               serviceCls.validateUser(formData) : user;
      //If user is not validated
      if(user.isValidated())
      {
         sForward = app_msgs.getMessage("screen.home");
         currTime = sdf.format(cal.getTime());
         logger.info(String.format("User [%s] logged in at [%s]", 
                                    user.getUsername(),
                                    currTime));
         user.setMessage(currTime);
      }
      else
      {
         // For those situations when a new user model exists inspite of the
         // user being logged out due to an inactive session
         htSess.removeAttribute("user");
         sForward = app_msgs.getMessage("screen.login");
      }
      htSess.setAttribute("user", user);
      
      return mapping.findForward(sForward);
   }
   
   /**
    * Logoff current user and end session
    * @param mapping The ActionMapping used to select this instance
    * @param actionForm The ActionForm bean for this request (if any)
    * @param request The HTTP request we are processing
    * @param response The HTTP response we are creating
    */
   public ActionForward endSession(ActionMapping mapping, ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
   {
      String sForward = app_msgs.getMessage("screen.login");
      HttpSession htSess = request.getSession(false);
      //Invalidate should do the following, but still
      //sometimes in an exception/error scenario this
      //attribute doesn't get removed.
      htSess.removeAttribute("user");
      htSess.invalidate();
     
      return mapping.findForward(sForward);
   }
   
}
